package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.service.Uservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public abstract class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Uservice {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean saveOrUpdateById(User user) {
        if (user.getId() < 0) {
            user.setCreate_time(LocalDateTime.now());
        }
        user.setUpdate_time(LocalDateTime.now());
        return saveOrUpdate(user);
    }
    @Override
    public Page<User> page(Integer current, Integer size, String username) {
        Page<User> page = new Page<>(current, size);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(username)) {
            queryWrapper.like(User::getUsername, username);
        }
        return page(page, queryWrapper);
    }
    @Override
    public boolean deleteBatchIds(List<Long> ids) {
        return removeByIds(ids);
    }
    @Override
    public User getUserByUsername(String username) {
        return getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
    }
    @Override
    public boolean register(User user) {
        User existUser = getUserByUsername(user.getUsername());
        if (existUser != null) {
            return false;
        }
        String encryptedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(encryptedPassword);

        user.setCreate_time(LocalDateTime.now());
        user.setUpdate_time(LocalDateTime.now());

        return save(user);
    }
    @Override
    public Map<String, Object> login(String username, String password) {
        User user = getUserByUsername(username);
        if (user == null) {
            return null;
        }
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!encryptedPassword.equals(user.getPassword())) {
            return null;
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", user);

        return result;
    }
}